<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form
      ref="queryForm"
      :model="queryParams"
      label-width="180px"
      size="small"
      :inline="true"
    >
      <el-row>
        <el-form-item label="编号">
          <el-input
            v-model="queryParams.id"
            placeholder="编号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="名称">
          <el-input
            v-model="queryParams.name"
            placeholder="名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="别名">
          <el-input
            v-model="queryParams.q"
            placeholder="别名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="queryParams.sex"
            clearable
            placeholder="请选择性别"
          >
            <el-option
              v-for="item in Sexoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="地址">
          <el-input
            v-model="queryParams.address"
            placeholder="请输入地址"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-select
            v-model="queryParams.memo"
            clearable
            placeholder="请选择备注"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-form-item>
        <button class="myel-button" @click="search">搜索</button>
        <!-- <el-button type="primary" icon="el-icon-search" size="mini" @click="search">搜索</el-button> -->
        <el-button icon="el-icon-refresh" size="mini" @click="reset"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 新增的按钮 -->
    <el-row :gutter="10" >
      <el-col :span="2">
        <button class="myel-button" @click="isaddshow">新增</button>
        <!-- <el-button type="primary" plan icon="el-icon-plus" size="mini" @click="isaddshow">新增</el-button> -->
      </el-col>
      <el-col :span="2">
        <button class="myel-button" @click="download">导出Excel</button>
        <!-- <el-button type="primary" size="mini" @click="download">导出Excel</el-button> -->
        <!-- <button type="button" class="kalacloudExportExcel-button" v-on:click="download">导出至 Excel</button> -->
      </el-col>
      <el-col :span="2">
        <div class="function-point-container">
          <button class="myel-button" @click="$refs.excelBtn.click()">
            批量导入
          </button>
          <!-- <el-button size="mini" type="primary" @click="$refs.excelBtn.click()">批量导入</el-button> -->
          <el-upload
            v-show="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            action
            :auto-upload="false"
            :show-file-list="false"
            :on-change="importData"
          >
            <span ref="excelBtn">导入EXCEL</span>
          </el-upload>
        </div>
      </el-col>
      <el-col :span="2">
        <button class="del-button" @click="AlldelsHeadle">批量删除</button>
        <!-- <el-button size="mini" icon="el-icon-delete" type="danger" @click="AlldelsHeadle">批量删除</el-button> -->
      </el-col>
    </el-row>

    <!-- 表单 -->
    <el-table
      :data="msgList"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="25"> </el-table-column>
      <el-table-column prop="id" label="编号" align="center">
      </el-table-column>
      <el-table-column prop="name" label="名称" align="center">
      </el-table-column>
      <el-table-column
        prop="q"
        label="别名"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="sex" label="性別" align="center" >
      </el-table-column>
      <el-table-column prop="address" label="地址" align="center">
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center">
      </el-table-column>
      <el-table-column prop="memo" label="备注" align="center">
      </el-table-column>

      <el-table-column
        label="操作"
        fixed="right"
        width="180"
        align="center"
       
      >
        <template slot-scope="scope">
          <button class="myel-button" @click="isupshow(scope.row)">修改</button>
          <button class="del-button" @click="delHeadle(scope.row)">删除</button>
          <!-- <el-button size="mini" icon="el-icon-edit" type="primary" @click="isupshow(scope.row)">修改</el-button> -->
          <!-- <el-button size="mini" icon="el-icon-delete" type="danger" @click="delHeadle(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!--添加和修改的弹出层 -->
    <el-dialog :title="title" :visible.sync="GainmsgVisible" width="50%">
      <!-- 内容区 -->
      <el-form ref="editMaterialListRef" :model="FromList" label-width="100px">
        <el-form-item label="名称" prop="planCheck">
          <el-input v-model="FromList.name"></el-input>
        </el-form-item>
        <el-form-item label="别名">
          <el-input v-model="FromList.q"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="FromList.sex" label="男">男</el-radio>
          <el-radio v-model="FromList.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="FromList.address"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="FromList.phone"></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-select v-model="FromList.memo" clearable placeholder="用户类型">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="GainmsgVisible = false">取 消</el-button>
        <button class="myel-button" style="height: 40px" @click="submit">
          确定
        </button>
        <!-- <el-button type="primary" @click="submit">确定</el-button> -->
      </span>
    </el-dialog>
    <el-pagination
      style="float: right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="FromlIMET.i"
      :page-size="FromlIMET.pagesize"
      layout="prev, pager, next, jumper"
      :total="FromlIMET.total"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  getMember,
  selectId,
  selectnameMe,
  delMember,
  addMember,
  updataMember,
} from "@/api/index";
import * as XLSX from "xlsx";

export default {
  created() {
    let openid = localStorage.getItem("openid");
    this.openid = openid;
    this.getList();
  },
  data() {
    return {
      // 搜索1,调用2
      isShow: 2,
      FromlIMET: {
        i: 1,
        pagesize: 10,
        total: 2480,
      },
      openid: null,
      // 模糊搜索的数据
      queryParams: {
        id: "",
        name: "",
        sex: "",
        memo: "",
        phone: "",
        address: "",
        q: "",
        i: 1,
        pagesize: 10,
      },
      Sexoptions: [
        {
          value: "男",
          label: "男",
        },
        {
          value: "女",
          label: "女",
        },
      ],
      value: "",
      // 重置按钮的数据
      resetParams: {
        getDate: null,
      },
      // 表格数据
      msgList: [],
      // 总条数
      total: 0,
      // 显示隐藏修改的弹出层
      GainmsgVisible: false,
      // 新增和修改标题
      title: "",
      // 全选删除
      ids: [],
      // 0添加1修改
      isChange: 0,
      FromList: {
        name: "",
        sex: "男",
        address: "",
        q: "",
        phone: "",
        memo: "",
      },
      options: [
        {
          value: "全部",
          label: "全部",
        },
        {
          value: "理事",
          label: "理事",
        },
        {
          value: "迁出",
          label: "迁出",
        },
        {
          value: "已故",
          label: "已故",
        },
        {
          value: "原理事",
          label: "原理事",
        },
        {
          value: "会员",
          label: "会员",
        },
      ],
    };
  },

  methods: {
    reset() {
      this.queryParams.i = 1;
      this.FromlIMET.i = 1;
      this.queryParams.id = "";
      this.queryParams.name = "";
      this.queryParams.sex = "";
      this.queryParams.memo = "";
      this.queryParams.phone = "";
      this.queryParams.q = "";
      this.queryParams.address = "";
      this.getList();
    },
    async handleSelectionChange(item) {
      this.ids = item;
    },
    AlldelsHeadle() {
      this.ids.forEach(async (v) => {
        const data = await delMember(v.id);
        if (data.data.code == 200) {
          this.getList();
        }
      });
      this.$message.success("删除成功！");
    },
    async delsHeadle() {
      const data = await delMember(this.ids);
      if (data.data.code == 200) {
        this.$message.success("删除成功！");
        this.getList();
      }
    },
    async search() {
      this.isShow = 1;
      if (
        this.queryParams.id == "" &&
        this.queryParams.address == "" &&
        this.queryParams.name == "" &&
        this.queryParams.sex == "" &&
        this.queryParams.memo == "" &&
        this.queryParams.phone == "" &&
        this.queryParams.s == ""
      ) {
        this.getList();
      } else if (this.queryParams.id !== "") {
        this.queryParams.i = 0;
        const { data: res } = await selectId(this.queryParams);
        this.FromlIMET.total = res.data.total;
        this.msgList = res.data.list;
        console.log(res);
      } else {
        this.queryParams.i = 1;
        const { data: res } = await selectnameMe(
          JSON.parse(JSON.stringify(this.queryParams))
        );
        console.log(res);
        this.FromlIMET.total = res.data.total;
        if (this.queryParams.memo) {
          const a = res.data.list
            .map((v) => {
              if (v.memo !== null) {
                return v;
              }
              return null;
            })
            .filter((v) => v !== null);
          this.msgList = a;
        } else {
          this.msgList = res.data.list;
        }
      }

      // this.msgList = res.data.list
      // console.log(this.msgList)
    },
    async search21() {
      this.isShow = 1;
      if (
        this.queryParams.name == "" &&
        this.queryParams.sex == "" &&
        this.queryParams.memo == "" &&
        this.queryParams.phone == "" &&
        this.queryParams.s == ""
      ) {
        this.getList();
      } else {
        const { data: res } = await selectnameMe(
          JSON.parse(JSON.stringify(this.queryParams))
        );
        console.log(res);
        this.FromlIMET.total = res.data.total;
        if (this.queryParams.memo) {
          const a = res.data.list
            .map((v) => {
              if (v.memo !== null) {
                return v;
              }
              return null;
            })
            .filter((v) => v !== null);
          this.msgList = a;
        } else {
          this.msgList = res.data.list;
        }
      }

      // this.msgList = res.data.list
      // console.log(this.msgList)
    },
    async getList() {
      this.isShow = 2;
      const { data: res } = await getMember(
        this.FromlIMET.i,
        this.FromlIMET.pagesize
      );
      this.FromlIMET.total = res.data.total;
      this.msgList = res.data.list;
    },

    isupshow(row) {
      this.title = "修改会员信息";
      this.isChange = 1;
      this.FromList = JSON.parse(JSON.stringify(row));
      this.GainmsgVisible = true;
    },
    isaddshow() {
      this.FromList = {};
      this.title = "添加会员";
      this.isChange = 0;
      this.GainmsgVisible = true;
    },
    async delHeadle(row) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该设备,是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const data = await delMember(row.id);
      console.log(data);
      if (data.data.code == 200) {
        this.$message.success("删除成功！");
        this.getList();
      }
    },
    async submit() {
      if (this.isChange === 0) {
        console.log("添加");
        // 添加
        const data = await addMember(JSON.parse(JSON.stringify(this.FromList)));
        if (data.data.code == 200) {
          this.$message({
            message: "新建成功!",
            type: "success",
          });
          this.getList();
          this.GainmsgVisible = false;
        }
      } else if (this.isChange === 1) {
        // 修改
        const data = await updataMember(
          JSON.parse(JSON.stringify(this.FromList))
        );
        console.log(data.data.code);
        if (data.data.code == 200) {
          this.$message({
            message: "修改成功!",
            type: "success",
          });
          this.getList();
          this.GainmsgVisible = false;
        }
      }
    },

    async importData(event) {
      const file = event.raw;
      if (file) {
        const loadingInstance = this.$loading({
          lock: true,
          text: "正在导入...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        try {
          await this.parseExcel(file);
          this.$message({
            message: "导入成功!",
            type: "success",
          });
          this.getList();
        } catch (error) {
          console.error("导入失败:", error.message);
          this.$message.error("导入失败，请检查文件格式。");
        } finally {
          loadingInstance.close();
        }
      }
    },
    async parseExcel(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (e) => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: "binary" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          if (jsonData.length > 0) {
            const objArray = jsonData.map((data) => ({
              id: data[0],
              memo: data[1],
              name: data[2],
              q: data[3],
              sex: data[4],
              address: data[5],
              phone: data[6],
            }));
            console.log(objArray);
            const promises = objArray.map(async (v) => {
              await addMember(JSON.parse(JSON.stringify(v)));
            });

            Promise.all(promises)
              .then(() => {
                resolve();

                location.reload();
              })
              .catch((error) => {
                reject(error);
              });
          } else {
            resolve();
          }
        };

        reader.onerror = (error) => {
          reject(error);
        };

        reader.readAsBinaryString(file);
      });
    },

    //   const file = event.raw
    //   if (file) {
    //     this.parseExcel(file)
    //   }
    // },
    // parseExcel(file) {
    //   const reader = new FileReader()

    //   reader.onload = e => {
    //     const data = e.target.result
    //     const workbook = XLSX.read(data, { type: 'binary' })
    //     const firstSheetName = workbook.SheetNames[0]
    //     const worksheet = workbook.Sheets[firstSheetName]
    //     const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })

    //     // 打印导入的数据
    //     if (jsonData.length > 0) {
    //       const objArray = jsonData.map(data => {
    //         return {
    //           memo: data[1],
    //           name: data[2],
    //           q: data[3],
    //           sex: data[4],
    //           address: data[5],
    //           phone: data[6]
    //         }
    //       })
    //       objArray.forEach(v => {
    //         addMember(JSON.parse(JSON.stringify(v))).then(res => {
    //           this.getList()
    //         })
    //         this.$message({
    //           message: '导入成功!',
    //           type: 'success'
    //         })
    //         location.reload()
    //       })
    //     }
    //   }

    //   reader.readAsBinaryString(file)
    // },
    // 方法3
    // async importData(event) {
    //   const file = event.raw
    //   if (file) {
    //     const loadingInstance = Loading.service({ fullscreen: true })
    //     try {
    //       const jsonData = await this.readFile(file)
    //       if (jsonData.length > 0) {
    //         await this.addMembers(jsonData)
    //         this.message('导入成功!', 'success')
    //         this.getList()
    //       }
    //     } catch (error) {
    //       console.error('导入失败:', error)
    //       this.$error('导入失败，请检查文件格式。', 'error')
    //     } finally {
    //       loadingInstance.close()
    //       location.reload()

    //     }
    //   }
    // },
    // readFile(file) {
    //   return new Promise((resolve, reject) => {
    //     const reader = new FileReader()
    //     reader.onload = e => {
    //       const data = e.target.result
    //       const workbook = XLSX.read(data, { type: 'binary' })
    //       const firstSheetName = workbook.SheetNames[0]
    //       const worksheet = workbook.Sheets[firstSheetName]
    //       const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
    //       resolve(jsonData)
    //     }
    //     reader.onerror = error => {
    //       reject(error)
    //     }
    //     reader.readAsBinaryString(file)
    //   })
    // },
    // async addMembers(jsonData) {
    //   const promises = jsonData.map(data => {
    //     return addMember({
    //       memo: data[1],
    //       name: data[2],
    //       q: data[3],
    //       sex: data[4],
    //       address: data[5],
    //       phone: data[6]
    //     })
    //   })
    //   await Promise.all(promises)
    // },
    async download() {
      this.queryParams.pagesize = 10000;
      const { data: res } = await selectnameMe(this.queryParams);
      this.queryParams.pagesize = 10;
      const modifiedMsgList = res.data.list.map((data) => ({
        序号: data.id,
        备注: data.memo,
        中文姓名: data.name,
        印尼文姓名: data.q,
        性别: data.sex,
        地址: data.address,
        电话: data.phone,
      }));

      const data = XLSX.utils.json_to_sheet(modifiedMsgList);
      const wb = XLSX.utils.book_new();
      const currentDate = new Date();
      const formattedDate = currentDate.toISOString().replace(/[:.]/g, "-");
      const timestamp = currentDate.getTime();

      const formattedTimestamp = String(timestamp).padStart(3, "0");

      const fileName = `kalacloudExportExcel_${formattedDate}_${formattedTimestamp}.xlsx`;
      XLSX.utils.book_append_sheet(wb, data, formattedDate);
      XLSX.writeFile(wb, fileName);
    },
    handleSizeChange(val) {},
    handleCurrentChange(val) {
      console.log((this.FromlIMET.i = val), (this.queryParams.i = val));
      this.FromlIMET.i = val; // 更新当前页码
      this.queryParams.i = val; // 更新当前页码
      if (this.isShow == 1) {
        this.search21();
      } else if (this.isShow == 2) {
        this.getList();
      }
    },
  },
};
</script>
<style scoped>
/* Element UI按钮的样式 */
.myel-button {
  display: inline-block;
  height: 29px;
  line-height: 6px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #409eff;
  color: #ffffff;
  outline: none;
  transition: 0.1s;
}

.myel-button:hover {
  background-color: #72b2f2;
  border-color: #c0c4cc;
  color: #ffffff;
}

.myel-button:active {
  background-color: #409eff;
  border-color: #c0c4cc;
  color: #ffffff;
}
.del-button {
  display: inline-block;
  height: 29px;
  line-height: 6px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f56c6c;
  color: #ffffff;
  outline: none;
  transition: 0.1s;
}

.del-button:hover {
  background-color: #f78989;
  border-color: #c0c4cc;
  color: #ffffff;
}

.del-button:active {
  background-color: #f78989;
  border-color: #c0c4cc;
  color: #ffffff;
}
</style>

